<?php

namespace App\Http\Controllers;

use App\Models\Options;
use App\Models\Questions;
use App\Models\Results;
use App\Models\Temp;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laracasts\Flash\Flash;

class AnswerController extends AppBaseController
{
    public function index() {
    	$temps = Temp::all();

    	return view('answer.index', compact('temps'));
    }

    public function answerTemps($tempId) {
    	$temp = Temp::with('questions.options')->find($tempId);
    	if($temp === null) {
    		Flash::error('问卷不存在');

    		return redirect('/');
	    }

	    $qm = new Questions();
	    foreach ($temp->questions as $k => &$v) {
    		$pq = $qm->where('next_id', $v->id)->where('temp_id', $tempId)->first();
    		$v->prevCode = $pq ? $pq->code : '0';
    		$nq = $v->nextQuestion;
    		$v->nextCode = $nq ? $nq->code : '0';
	    }
	    $total = $temp->questions->count();

	    return view('answer.answer', compact('temp', 'total'));
    }

    public function store(Request $req) {
    	$data = $req->get('res');
    	$ip = $req->ip();
    	$ip = ip2long($ip);

    	$tempId = $req->get('temp_id');
    	$temp = Temp::find($tempId);
    	if($temp === null) {
    		return [
    			'code' => 404,
			    'msg' => '问卷不存在'
		    ];
	    }

	    $save = [];

    	DB::beginTransaction();
	    $resModel = new Results();
    	foreach ($data as $k => $v) {
    		$q = Questions::find($k);
    		if($q === null) {
    			DB::rollBack();
    			return [
    				'code' => 404,
				    'msg' => '问题数据错误'
			    ];
		    }

		    foreach ($v as $kk => $vv) {
    			if($q->type === Questions::SIMPLE_CHECK || $q->type === Questions::MULTI_CHECK) {
				    $opt = Options::find($vv);
				    if($opt === null) {
				    	DB::rollBack();
					    return [
						    'code' => 404,
						    'msg' => '选项错误'
					    ];
				    }

				    $save[$kk]['option_id'] = $vv;
				    $save[$kk]['answer'] = $opt->content;

				    unset($opt);
			    } else {
				    $save[$kk]['answer'] = $vv;
			    }

    			$save[$kk]['temp_id'] = $tempId;
    			$save[$kk]['temp_name'] = $temp->name;
    			$save[$kk]['question_id'] = $k;
    			$save[$kk]['question'] = $q->content;
    			$save[$kk]['ip'] = $ip;

    			foreach ($save as $resData) {
				    $resModel->create($resData);
			    }

			    unset($save);
		    }

		    unset($q);
	    }

	    DB::commit();

    	return [
    		'code'  =>  200,
		    'msg'   =>  '提交成功'
	    ];
    }
}
